package com.frxuexi.shop.view

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.db.OrderEntity
import com.frxuexi.base.entity.CartBean
import com.frxuexi.base.entity.CreateOrderBean
import com.frxuexi.base.entity.CreateOrderReqBean
import com.frxuexi.base.entity.GetPreOrderBean
import com.frxuexi.base.entity.OrderDetail
import com.frxuexi.base.entity.PreOrderBean
import com.frxuexi.base.entity.PreOrderRespBean
import com.frxuexi.base.mvi.BaseFragment
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.DateTimeUtils
import com.frxuexi.shop.R
import com.frxuexi.shop.adapter.CartAdapter
import com.frxuexi.shop.databinding.FragmentCartBinding
import com.frxuexi.shop.intent.CartIntent
import com.frxuexi.shop.intent.OrderIntent
import com.frxuexi.shop.viewmodel.CartViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class CartFragment : BaseFragment<FragmentCartBinding, CartIntent, CartViewModel>() {
    val cartAdapter by lazy { CartAdapter() }

    var sum=0.0

    var orderNo=""
    override fun getVM(): CartViewModel {
        return viewModels<CartViewModel>().value
    }

    override fun getBind(): FragmentCartBinding {
        return FragmentCartBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.DEFAULT -> {
                                val cartBean = it.data as CartBean
                                cartAdapter.apply {
                                    data.clear()
                                    addData(cartBean.list)
                                    notifyDataSetChanged()
                                }
                                binding.cartNum.setText("购物车（${cartBean.list.size}）")
                            }
                            RequestType.UPDATE->{
                                Log.i("lr","增加成功")
                            }
                            RequestType.DELETE->{
                                vm.sendIntent(CartIntent.getCarts(1))
                            }
                            RequestType.ADD->{
                                ToastUtils.showLong("下单成功")
                            }
                            RequestType.PREORDER->{
                                val bean = it.data as PreOrderRespBean
                                orderNo=bean.preOrderNo
                                vm.sendIntent(CartIntent.getPreOrder(bean.preOrderNo))
                            }
                            RequestType.GETPREORDER->{
                                val bean = it.data as GetPreOrderBean
                                val reqBean = CreateOrderReqBean(
                                    bean.orderInfoVo.addressId,
                                    bean.orderInfoVo.userCouponId,
                                    bean.orderInfoVo.remark?:"",
                                    "alipay",
                                    "yue",
                                    bean.orderInfoVo.phone,
                                    orderNo,
                                    bean.orderInfoVo.realName,
                                    1,
                                    0,
                                    false
                                )
                                vm.sendIntent(CartIntent.createOrder(reqBean))
                            }
                            RequestType.CREATEORDER->{
                                val orderBean = it.data as CreateOrderBean
                                cartAdapter.data.filter { it.isCheck }.forEach {
                                    vm.sendIntent(CartIntent.addOrder(OrderEntity(null,it.productId,orderBean.orderNo,it.image,it.storeName,it.cartNum,it.price.toDouble(),it.cartNum*it.price.toDouble(),DateTimeUtils.getDateTime(System.currentTimeMillis()),1)))
                                }
                                vm.sendIntent(CartIntent.getCarts(1))
                            }
                            else -> {}
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        binding.rvCar.apply {
            adapter = cartAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }
        vm.sendIntent(CartIntent.getCarts(1))

        binding.cbAll.setOnClickListener {
            cartAdapter.data.forEach {
                it.isCheck = binding.cbAll.isChecked
            }
            cartAdapter.notifyDataSetChanged()

            if (binding.cbAll.isChecked) {
                binding.buyNow.setText("结算(${cartAdapter.data.size})")
                sum=cartAdapter.data.sumOf {
                    it.cartNum*it.price.toDouble()
                }
            } else {
                binding.buyNow.setText("结算(0)")
                sum=0.0
            }
            binding.amountAll.setText("合计：￥${sum}")
        }

        binding.cartDelete.setOnClickListener {
            val ids = mutableListOf<Int>()
            cartAdapter.data.forEach {
                if(it.isCheck){
                    ids.add(it.id)
                }
            }
            vm.sendIntent(CartIntent.deleteCart(ids))
        }

        cartAdapter.addChildClickViewIds(R.id.car_check_box, R.id.car_sub, R.id.car_add)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = cartAdapter.data.get(position)
            when (view.id) {
                R.id.car_check_box -> {
                    item.isCheck = !item.isCheck
                    binding.cbAll.isChecked = cartAdapter.data.all { it.isCheck }
                    binding.buyNow.setText("结算(${cartAdapter.data.count { it.isCheck }})")

                    sum=cartAdapter.data.filter { it.isCheck }.sumOf {
                        it.cartNum*it.price.toDouble()
                    }
                    binding.amountAll.setText("合计：￥${sum}")
                }

                R.id.car_sub -> {
                    if(item.cartNum==1){
                        ToastUtils.showLong("购买数量不能小于1")
                        return@setOnItemChildClickListener
                    }
                    item.cartNum-=1
                    cartAdapter.notifyItemChanged(position)
                    vm.sendIntent(CartIntent.updateCart(item.id,item.cartNum))
                    if(item.isCheck){
                        sum-=item.price.toDouble()
                        binding.amountAll.setText("合计：￥${sum}")
                    }
                }

                R.id.car_add -> {
                    if(item.cartNum==item.stock){
                        ToastUtils.showLong("已达到最大库存量")
                        return@setOnItemChildClickListener
                    }
                    item.cartNum+=1
                    cartAdapter.notifyItemChanged(position)
                    vm.sendIntent(CartIntent.updateCart(item.id,item.cartNum))
                    if(item.isCheck){
                        sum+=item.price.toDouble()
                        binding.amountAll.setText("合计：￥${sum}")
                    }
                }
            }
        }

        binding.buyNow.setOnClickListener {
            val ids = mutableListOf<Int>()
            cartAdapter.data.filter { it.isCheck }.forEach {
                val preOrderBean = PreOrderBean(
                    preOrderType = "shoppingCart",
                    productId = it.productId,
                    shoppingCartId = it.id,
                    orderDetails = listOf<OrderDetail>(
                        OrderDetail(preOrderType = "shoppingCart",
                            productId = it.productId,
                            shoppingCartId = it.id)
                    )
                )
                vm.sendIntent(CartIntent.preOrder(preOrderBean))
//                ids.add(it.id)
//                vm.sendIntent(CartIntent.deleteCart(ids))
//                vm.sendIntent(CartIntent.addOrder(OrderEntity(null,it.productId,it.image,it.storeName,it.cartNum,it.price.toDouble(),it.cartNum*it.price.toDouble(),DateTimeUtils.getDateTime(System.currentTimeMillis()),1)))
            }
        }


    }

}